const { ajax, formatTime } = require("../../utils/index");

// 维修状态的对应关系
const statusMap = {
  0: "待维修",
  1: "待处理",
  2: "处理中",
  3: "已完成"
};

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabNow: 0,
    tabList: [
      {
        label: '待维修',
        value: 0,
      },
      {
        label: '待处理',
        value: 1,
      },
      {
        label: '处理中',
        value: 2,
      },
      {
        label: '已完成',
        value: 3
      }
    ],
    list: [],
    isWorker: false,
    showStartModal: false,
    showFinishModal: false,
    desc: '',
    img_url: '',
    buildingNumberList: [],
    repairList: [],
    buildingMap: {},
    repairMap: {},
    start_info: '',
    start_img: '',
    finish_info: '',
    finish_img: '',
    currentId: '',
  },

  viewDetail(e) {
    const item = e.currentTarget.dataset.item;
    console.log('item', item);
    wx.navigateTo({
      url: `../repairResult/repairResult?info=${JSON.stringify(item)}`,
    })

  },

  uploadImg(e) {
    wx.chooseMedia({
      mediaType: ['image'],
      success: (res) => {
        // const tempFilePaths = res.tempFilePaths
        console.log('choosemedia', res);
        wx.uploadFile({
          url: 'http://localhost:8080/common/upload',
          filePath: res.tempFiles[0].tempFilePath,
          name: 'file',
          success: (res) => {
            try {
              const data = JSON.parse(res.data);
              if (data.code === 200) {
                if (this.data.tabNow === 1) {
                  this.data.start_img = data.fileName
                } else if (this.data.tabNow === 2) {
                  this.data.finish_img = data.fileName
                }

                //  console.log('data',  this.data.start_img );

              }
            } catch (error) {
              console.error('Failed to parse response:', error);
            }
          },
          fail: (err) => {
            console.log('Upload failed:', err);
          }
        });
      }
    })


  },

  getDesc(e) {
    if (this.data.tabNow === 1) {
      this.setData({
        start_info: e.detail.value
      })
    } else if (this.data.tabNow === 2) {
      this.setData({
        finish_info: e.detail.value
      })
    }
  },

  toShowStartModal(e) {
    this.setData({
      showStartModal: !this.data.showStartModal,
      currentId: e.currentTarget.dataset.item.id
    })
  },

  toShowFinishModal(e) {
    this.setData({
      showFinishModal: !this.data.showFinishModal,
      currentId: e.currentTarget.dataset.item.id
    })
  },

  async startService(e) {
    // const { status, id } = e.currentTarget.dataset;
    const { tabNow, start_img, start_info, finish_img, finish_info } = this.data;

    let img = ''
    let info = ''
    let url = ''
    let params = {
      id: this.data.currentId
    }
    if (tabNow === 1) {
      img = start_img
      info = start_info
      params.start_img = img
      params.start_info = info
      url = '/api/repair-orders/updateStartInfo'
    } else if (tabNow === 2) {
      img = finish_img
      info = finish_info
      params.finish_img = img
      params.finish_info = info
      url = '/api/repair-orders/updateFinishInfo'
    }
    console.log('f', finish_info, finish_img);
    if (!img || !info) {
      wx.showToast({
        title: '存在必填项未填写!',
        icon: 'none'
      })
      return;
    }

    const { data } = await ajax(url, 'POST', params);
    console.log('...data', data);
    if (data.code === 200) {
      wx.showToast({
        title: '操作成功!',
        icon: 'none'
      })
      if (this.data.tabNow === 1) {
        this.setData({
          start_img: '',
          start_info: '',
          showStartModal: false
        })
      } else if (this.data.tabNow === 2) {
        this.setData({
          finish_info: '',
          finish_img: '',
          showFinishModal: false
        })
      }
      this.fetchRepairOrders()
    } else {
      wx.showToast({
        title: '操作失败!',
        icon: 'none'
      })
    }
  },

  onTabsChange(e) {
    this.setData({
      tabNow: e.detail.value
    })
    this.fetchRepairOrders()
  },

  // 获取维修订单列表数据
  async fetchRepairOrders() {
    const loginInfo = wx.getStorageSync('loginInfo');
    // console.log(loginInfo);
    const { data } = await ajax('/api/repair-orders/list', 'GET');

    if (data.code === 200) {
      const list = data.data.filter((item) =>
        item.status === this.data.tabNow && item.workerName === loginInfo.name
      )
      this.setData({ list: list })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.fetchBuildingNumbers();
    this.fetchRepairTypes();
    const loginInfo = wx.getStorageSync('loginInfo');
    this.fetchRepairOrders(loginInfo.role === 0 ? 0 : 1);
    if (loginInfo) {
      const { role } = loginInfo;
      if (role === 1) {
        this.setData({
          tabNow: 1,
          tabList: [{
            label: '待处理',
            value: 1,
          },
          {
            label: '处理中',
            value: 2,
          },
          {
            label: '已完成',
            value: 3
          }],
          isWorker: true
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  //查楼栋号
  async fetchBuildingNumbers() {
    try {
      const response = await ajax('/api/dict-data/building-number', 'GET');
      // console.log('res', response);
      if (response.data.code === 200) {
        const { data } = response.data
        this.setData({
          buildingNumberList: data.map(item => ({
            label: item.dictLabel,
            value: item.dictValue
          }))
        });
        const blist = []
        this.data.buildingNumberList.forEach((item) => {
          blist[item.value] = item.label
        })
        this.setData({
          buildingMap: blist
        })
      } else {
        console.error('Failed to fetch building numbers:', response.msg);
      }
    } catch (error) {
      console.error('Error fetching building numbers:', error);
    }
  },
  //查故障类型
  async fetchRepairTypes() {
    try {
      const response = await ajax('/api/dict-data/repair-type', 'GET');
      if (response.data.code === 200) {
        const { data } = response.data
        this.setData({
          repairList: data.map(item => ({
            label: item.dictLabel,
            value: item.dictValue
          }))
        });
        const rlist = []
        this.data.repairList.forEach((item) => {
          rlist[item.value] = item.label
        })
        this.setData({
          repairMap: rlist
        })
      } else {
        console.error('Failed to fetch repair types:', response.msg);
      }
    } catch (error) {
      console.error('Error fetching repair types:', error);
    }
  },
})